package server;

import catalina.MappedContext;
import catalina.MappedHost;
import catalina.Mapper;

import java.io.InputStream;
import java.net.Socket;

public class RequestProcessor extends Thread {

    private Socket socket;
    private int port;
    private catalina.Mapper mapper;

    public RequestProcessor(Socket socket, int port, Mapper mapper) {
        this.socket = socket;
        this.port = port;
        this.mapper = mapper;
    }

    @Override
    public void run() {
        try (InputStream inputStream = socket.getInputStream()) {

            // 封装Request对象和Response对象
            Request request = new Request(inputStream);
            Response response = new Response(socket.getOutputStream());


            System.out.println(request.getUrl());
            // 静态资源处理
//            HttpServlet httpServlet = mapper.getHost(request.getUrl());

            Boolean isServletRequest = false;
            MappedHost host = mapper.getHost(request.getHost());
            if (host != null) {
                if (port == request.getPort()) {
                    String webAppName = request.getUrl().split("/")[1];
                    MappedContext context = host.getContext(webAppName);
                    if (context != null) {
//                        context.getWrapper()

                        // 动态资源servlet请求
                        HttpServlet httpServlet = context.getWrapper(request.getUrl().replace("/" + webAppName, ""));
                        if (httpServlet != null) {
                            isServletRequest = true;
                            httpServlet.service(request, response);
                        }
                    }
                }
            }

            if (!isServletRequest) {
                response.outputHtml(request.getUrl());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
